/**
 * 
 */
package trungsi.gea.photos.client

import org.json.JSONObject
import java.awt.image.BufferedImageimport java.awt.Graphicsimport java.awt.Graphics2Dimport java.awt.RenderingHintsimport org.json.JSONArray
import java.awt.Image
import javax.imageio.ImageIO

/**
 * @author trungsi
 *
 */
public class Service {

	def serverUrl = ''
	
	def newRemoteFolder(folderName) {
		println folderName.encodeURL()
		def text = ("$serverUrl/folder-admin?save=&folder.name=" + folderName.encodeURL()).toURL().text
		println text
		new JSONObject(text).getJSONObject('folder').getString('id')
	}
	
	def getRemoteFolders() {
		def text = "$serverUrl/folder?list=".toURL().getText('UTF-8')
		println text
		toArray(new JSONObject(text))
	}
	
	def updateRemoteFolderName(folderId, folderName) {
		def text = ("$serverUrl/folder-admin?save=&folder=" + folderId + "&folder.name=" + folderName.encodeURL()).toURL().text
		
		new JSONObject(text).getBoolean('success')
	}
	
	def uploadFile(file, remoteFolder) {
		def boundary = MultipartFormOutputStream.createBoundary()
        def connection = MultipartFormOutputStream.createConnection("$serverUrl/photo-admin".toURL())
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("Content-Type", MultipartFormOutputStream.getContentType(boundary));
    
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Cache-Control", "no-cache");
        
        def output = new MultipartFormOutputStream(connection.outputStream, boundary)
        output.writeField("save", "")
        output.writeField("photo.name", file.name)
        output.writeField("photo.folder", remoteFolder)
        //output.writeFile("photoFile", "", file)
        output.writeFile("slideshowFile", "", "slideshowFile", resize(file, 800, 600))
        output.writeFile("thumbnailFile", "", "thumbnailFile", resize(file, 100, 100))
        output.close()
        try {
            println connection.inputStream.text
        } catch (e) {
            println e
            println connection.errorStream.text
        }
	}
	
	def uploadFiles(files, remoteFolder, onUploadFileStart) {
		int index = 1
		files.each {file ->
			println "Uploading to folder $remoteFolder : $file ${index++}/${files.size} "
			onUploadFileStart?.call(file)
			uploadFile(file, remoteFolder)
			//sleep 500
		}
	}
	
	def resize(file, width, height) {
		ImageUtils.downSize(file, width, height)
	}
	
	def getPhotos(folderId, after = null) {
		JSONConverter.convert(
				new JSONObject(
						("$serverUrl/photo?list=&folder=" + folderId + (after ? "&after=" + after : "")).toURL().text))
	}
	
	def getThumbnailUrl(photoId) {
		("$serverUrl/photo?showThumbnail=&photo=" + photoId).toURL()
	}
	
	def getSlideshowUrl(photoId) {
		("$serverUrl/photo?showSlideshow=&photo=" + photoId).toURL()
	}
	
	def getCoverUrl(folderId) {
		("$serverUrl/folder?cover=&folder=$folderId").toURL()
	}
	
	def deleteFolder(folderId) {
		def text = "$serverUrl/folder-admin?delete=&folder=$folderId".toURL().text
		println text
		def json = new JSONObject(text)
		[success : json.getBoolean('success'), error : json.has('error') ? json.getString('error') : '']
	}
	
	def deletePhoto(photoId) {
		def text = "$serverUrl/photo-admin?delete=&photo=$photoId".toURL().text
		println text
		def json = new JSONObject(text)
		[success : json.getBoolean('success'), error : json.has('error') ? json.getString('error') : '']
	}
	
	static def toArray(json) {
		JSONConverter.convert(json).folders
    }
}
